package com.hd.crdao.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.hd.crdao.R;
import com.hd.crdao.base.BaseActivity;
import com.hd.crdao.bean.AlipayBean;
import com.hd.crdao.bean.MealListBean;
import com.hd.crdao.bean.WXPayBean;
import com.hd.crdao.config.Constants;
import com.hd.crdao.utils.ALog;
import com.hd.crdao.utils.MyToast;
import com.hd.crdao.utils.PayResult;
import com.hd.crdao.utils.SPUtils;
import com.hd.crdao.utils.UIUtils;
import com.hd.crdao.view.ExpandHeadView;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;


/**
 *
 *@author Administrator
 *@date 2017/6/26 0026
 */
public class FirmOrderActivity extends BaseActivity implements CompoundButton.OnCheckedChangeListener {
    @BindView(R.id.head)
    ExpandHeadView mHead;
    @BindView(R.id.tv_vin)
    TextView mTvVin;
    @BindView(R.id.rl)
    RelativeLayout mRl;
    @BindView(R.id.cb_mealpay)
    CheckBox mCbMealpay;
    @BindView(R.id.meal_count)
    TextView mMealCount;
    @BindView(R.id.rl_meal)
    RelativeLayout mRlMeal;
    @BindView(R.id.cb_alipay)
    CheckBox mCbAlipay;
    @BindView(R.id.rl_alipay)
    RelativeLayout mRlAlipay;
    @BindView(R.id.cb_weixin)
    CheckBox mCbWeixin;
    @BindView(R.id.rl_weixin)
    RelativeLayout mRlWeixin;
    @BindView(R.id.commit)
    Button mCommit;

    public String mBusinessid;
    public String mVin;
    public String mBuyid;
    public String mPayListId;
    public MealListBean mMealListBean;

    //商户APP工程中引入微信JAR包，调用API前，需要先向微信注册您的APPID，代码如下
    final IWXAPI msgApi = WXAPIFactory.createWXAPI(UIUtils.getContext(), null);

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    public AlipayBean mAlipayBean;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        Toast.makeText(FirmOrderActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        Intent i = new Intent(UIUtils.getContext(),PayResultActivity.class);
                        i.putExtra("datatime",mAlipayBean.getDatatime());
                        i.putExtra("plorder",mAlipayBean.getPlorder());
                        i.putExtra("plMethod",mAlipayBean.getPlMethod());
                        i.putExtra("vin",mVin);
                        startActivity(i);
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(FirmOrderActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
            }
        }
    };



    @Override
    protected int getLayoutId() {
        return R.layout.activity_frim_order;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
    }

    @Override
    protected void initListener() {
        mHead.getLeftArrowLL().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mCbMealpay.setOnCheckedChangeListener(this);
        mCbAlipay.setOnCheckedChangeListener(this);
        mCbWeixin.setOnCheckedChangeListener(this);
    }

    @Override
    protected void initData() {
        mBusinessid = SPUtils.getString("businessid", "");
        //获取意图传递过来的值
        mVin = getIntent().getStringExtra("vin");
        mBuyid = getIntent().getStringExtra("buyid");
        mPayListId = getIntent().getStringExtra("payListId");
//        int caTimes = getIntent().getIntExtra("caTimes", 0);
        mTvVin.setText("VIN : "+mVin);
        //获取套餐可用条数
        getMealCanUseCount();
    }

    /**
     * 获取套餐的可用条数
     */
    private void getMealCanUseCount() {

        OkHttpUtils.post().url(Constants.MEALLIST_URL).addParams("sign",Constants.SIGN).addParams("carBusinessId", mBusinessid)
                .addParams("serviceTypeId", "1").build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                mCbAlipay.setChecked(true);
                MyToast.show("加载数据失败,请检查网络...");
            }
            @Override
            public void onResponse(String response, int id) {
                ALog.d(response);
                Gson gson = new Gson();
                mMealListBean = gson.fromJson(response, MealListBean.class);
                String success = mMealListBean.getSuccess();
                String message = mMealListBean.getMessage();
                if (TextUtils.equals("00", success)) {
                    List<MealListBean.CbAccountsBean> cbAccounts = mMealListBean.getCbAccounts();
                    if(cbAccounts.size()!=0){
                        int caTimes = cbAccounts.get(0).getCaTimes();
                        mRlMeal.setVisibility(View.VISIBLE);
                        mMealCount.setText("剩余条数("+caTimes+")条");
                        mCbMealpay.setChecked(true);
                    }else {
                        mRlMeal.setVisibility(View.GONE);
                        mCbAlipay.setChecked(true);
                    }
                } else {
                    MyToast.show(message);
                }
            }
        });
    }

    @OnClick(R.id.commit)
    public void onViewClicked() {
        if(mCbMealpay.isChecked()){
            //通过套餐支付
            ToMealPay();
        }else if(mCbAlipay.isChecked()){
            ToAlipay();
        }else if(mCbWeixin.isChecked()){
            if (! msgApi.isWXAppInstalled()) {
                MyToast.show("请前往应用商店下载微信");
            } else if (!msgApi.isWXAppSupportAPI()) {
                MyToast.show("当前版本微信不支持支付");
            }else {
                ToWeixinPay();
            }

        }
    }

    /**
     * 通过套餐支付
     */
    private void ToMealPay() {
        OkHttpUtils.post().url(Constants.CONFIRMPAY_URL).addParams("carBusinessId",mBusinessid).addParams("serviceTypeId","1")
                .addParams("plMethod", "T").addParams("plRelationid",mBuyid).addParams("amount","10").addParams("vinCode",mVin)
                .addParams("payListId",mPayListId).addParams("sign",Constants.SIGN).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                MyToast.show("请求失败,请检查网络...");
            }

            @Override
            public void onResponse(String response, int id) {
                ALog.d(response);
                try {
                    JSONObject jsonObject= new JSONObject(response);
                    String success = (String) jsonObject.get("success");
                    String message = (String) jsonObject.get("message");
                    if(TextUtils.equals("00",success)){
                        String datatime = (String) jsonObject.get("datatime");
                        String plorder = (String) jsonObject.get("plorder");
                        String plMethod = (String) jsonObject.get("plMethod");
                        //跳转到支付结果界面
                        Intent i = new Intent(UIUtils.getContext(),PayResultActivity.class);
                        i.putExtra("datatime",datatime);
                        i.putExtra("plorder",plorder);
                        i.putExtra("plMethod",plMethod);
                        i.putExtra("vin",mVin);
                        startActivity(i);
                        finish();
                    }else {
                        MyToast.show(message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     *跳转到微信支付
     */

    private void ToWeixinPay() {
        OkHttpUtils.post().url(Constants.CONFIRMPAY_URL).addParams("carBusinessId",mBusinessid).addParams("serviceTypeId","1")
                .addParams("plMethod", "W").addParams("plRelationid",mBuyid).addParams("amount","10").addParams("vinCode",mVin)
                .addParams("payListId",mPayListId).addParams("sign",Constants.SIGN).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                MyToast.show("请求失败,请检查网络...");
            }

            @Override
            public void onResponse(String response, int id) {
                ALog.d(response);
                Gson gson = new Gson();
                WXPayBean wxPayBean = gson.fromJson(response, WXPayBean.class);
                String datatime = wxPayBean.getDatatime();  //查询时间
                String plMethod = wxPayBean.getPlorder();      //订单编号
                SPUtils.saveString("payinfo","W"+","+mVin+","+plMethod+","+datatime);
                String success = wxPayBean.getSuccess();
                String message = wxPayBean.getMessage();
                if(TextUtils.equals("00",success)){
                    WXPayBean.WxmessageBean wxmessage = wxPayBean.getWxmessage();
                    //调起支付
                    PayReq request = new PayReq();
                    request.appId = wxmessage.getAppid();
                    request.partnerId = wxmessage.getPartnerid();
                    request.prepayId= wxmessage.getPrepayid();
                    request.packageValue = wxmessage.getPackageX();
                    request.nonceStr=wxmessage.getNoncestr();
                    request.timeStamp= String.valueOf(wxmessage.getTimestamp());
                    request.sign= wxmessage.getSign();
                    // 将该app注册到微信
                    msgApi.registerApp(Constants.APP_ID);
                    msgApi.sendReq(request);
                }else {
                    MyToast.show(message);
                }
            }
        });

    }

    /**
     * 跳转到支付宝支付
     */
    private void ToAlipay() {
        OkHttpUtils.post().url(Constants.CONFIRMPAY_URL).addParams("carBusinessId",mBusinessid).addParams("serviceTypeId","1")
                .addParams("plMethod", "Z").addParams("plRelationid",mBuyid).addParams("amount","10").addParams("vinCode",mVin)
                .addParams("payListId",mPayListId).addParams("sign",Constants.SIGN).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                MyToast.show("请求失败,请检查网络...");
            }

            @Override
            public void onResponse(String response, int id) {
                ALog.d(response);
                Gson gson = new Gson();
                mAlipayBean = gson.fromJson(response, AlipayBean.class);
                String success = mAlipayBean.getSuccess();
                String message = mAlipayBean.getMessage();
                if(TextUtils.equals("00",success)){
                    final String orderInfo = mAlipayBean.getData();   // 订单信息
                    Runnable payRunnable = new Runnable() {

                        @Override
                        public void run() {
                            PayTask alipay = new PayTask(FirmOrderActivity.this);
                            Map<String, String> result = alipay.payV2(orderInfo,true);
                            Message msg = new Message();
                            msg.what = SDK_PAY_FLAG;
                            msg.obj = result;
                            mHandler.sendMessage(msg);
                        }
                    };
                    // 必须异步调用
                    Thread payThread = new Thread(payRunnable);
                    payThread.start();
                }else {
                    MyToast.show(message);
                }
            }
        });
    }


    //checkbox选中状态改变的监听
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.cb_alipay:
                if (isChecked) {
                    mCbAlipay.setChecked(true);
                    mCbWeixin.setChecked(false);
                    mCbMealpay.setChecked(false);
                }
                break;
            case R.id.cb_weixin:
                if (isChecked) {
                    mCbWeixin.setChecked(true);
                    mCbAlipay.setChecked(false);
                    mCbMealpay.setChecked(false);
                }
                break;
            case R.id.cb_mealpay:
                if (isChecked) {
                    mCbMealpay.setChecked(true);
                    mCbWeixin.setChecked(false);
                    mCbAlipay.setChecked(false);
                }
                break;
        }
    }
}
